<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import Player from 'xgplayer'
import HlsPlayer from 'xgplayer-hls.js'

const props = defineProps({
  type: {
    type: String,
    default: 'video'
  },
  config: {
    type: Object,
    default() {
      return { id: 'mse', url: '' }
    }
  }
})

const emits = defineEmits(['player'])

const player = ref(null)

watch(
  () => props.config,
  () => {
    init()
  },
  { deep: true }
)

function init() {
  if (props.config.url) {
    if (props.type === 'video') {
      player.value = new Player(props.config)
    } else {
      player.value = new HlsPlayer(props.config)
    }
    emits('player', player.value)
  }
}

function destroy() {
  player.value && typeof player.value.destroy === 'function' && player.value.destroy()
}

onMounted(() => {
  init()
})

onUnmounted(() => {
  destroy()
})
</script>

<template>
  <div :id="config.id"></div>
</template>

<style lang="scss" scoped>
:deep(.xgplayer-live) {
  display: none !important;
}
</style>
